/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.FeaturedList;
import org.cx1.model.Listing;
import org.cx1.model.Place;
import org.cx1.model.utils.FeaturedListComparator;
import org.cx1.model.utils.ListingComparator;
import org.cx1.model.utils.SearchFilter;
import org.cx1.model.utils.SearchOption;
import org.cx1.model.utils.SearchResult;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IFeaturedService;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.ISearchService;
import org.cx1.service.impl.DListingService;
import org.cx1.service.impl.DSearchService;
import org.cx1.service.impl.MFeaturedService;
import org.cx1.service.impl.MListingService;
import org.cx1.service.impl.MSearchService;
import org.cx1.service.utils.UAgentInfo;
import org.cx1.web.controller.action.HomeAction;
import org.cx1.web.utils.SessionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author ECH
 */
public class HomeController extends BaseController {
    
    //private IListingService listingService = new MListingService();
    //private ISearchService searchService = new MSearchService();
    private IFeaturedService featuredService = new MFeaturedService();
    
    private IListingService listingService = new DListingService();
    private ISearchService searchService = new DSearchService();
    
    public HomeController() {
        
    }
    
    protected ModelAndView handleRequestInternal( HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
        
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();
        
        String userID = SessionUtils.getUserID(request.getSession());
        if (!StringUtils.isEmpty(userID)) {
            map.put("loggedin", true);
        }
        
        int action = StringUtils.isEmpty( request.getParameter("a") ) ? 0 : Integer.parseInt(request.getParameter("a"));
        
        switch (action) {
            case HomeAction.HOME: {
                home(mav, map, request);
                break;
            }
            case HomeAction.SEARCH: {
                search(mav, map, request);
                break;
            }
            case HomeAction.TERMS: {
                terms(mav, map, request);
                break;
            }  
            case HomeAction.PRIVACY: {
                privacy(mav, map, request);
                break;
            }  
            case HomeAction.WORKS: {
                works(mav, map, request);
                break;
            } 
            case HomeAction.RULES: {
                rules(mav, map, request);
                break;
            } 
            case HomeAction.FEATURED: {
                featured(mav, map, request);
                break;
            } 
            default: {
                home(mav, map, request);
                break;
            }
        }        
        
        Random rand = new Random();
        int splashRand = (int) (Math.random() * SystemProperties.SPLASH_COUNT_MAX + 1);
        
        map.put("splashMax", SystemProperties.SPLASH_COUNT_MAX);
        map.put("splashRand", splashRand == 0? 1 : splashRand);
        
        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        map.put("props", this.getSystemProperties());
        
        mav.addObject("model", map);
        return mav;
    }
    
    private void home(ModelAndView mav, Map map, HttpServletRequest request) {        
        try {            
            ServiceResponse<List<FeaturedList>> response2 = featuredService.readAllFeaturedList(0, 0);  
            List<Listing> listings = new ArrayList<Listing>();              
            List<FeaturedList> featuredLists = response2.getResponse();

            if (featuredLists != null && featuredLists.size() > 0) {
                Collections.sort(featuredLists, new FeaturedListComparator());
                for (FeaturedList featured : featuredLists) {
                    listings.add(listingService.read(featured.getListingID()).getResponse());                
                }
            }         
            map.put("listings", trimListingsData(listings)); 

            if (this.isThisRequestCommingFromAMobileDevice(request)) {
                mav.setViewName("home_mobile");
            }            
        }   
        catch (Exception ex) {  
            
        }
    }
    
    private void search(ModelAndView mav, Map map, HttpServletRequest request) {
        
        SearchFilter filter = new SearchFilter();
        
        String sr1 = StringUtils.isEmpty(request.getParameter("sr1")) ? "" : request.getParameter("sr1");
        String sr2 = StringUtils.isEmpty(request.getParameter("sr2")) ? "" : request.getParameter("sr2");
        
        String prL = request.getParameter("pr-l");
        String prU = request.getParameter("pr-u");      
                
        String sqL = request.getParameter("sq-l");
        String sqU = request.getParameter("sq-u");  
        
        String brL = request.getParameter("br-l");
        String brU = request.getParameter("br-u");  
        
        String bhL = request.getParameter("bh-l");
        String bhU = request.getParameter("bh-u");  
        
        String frRent = request.getParameter("fr-rent");
        String frSale = request.getParameter("fr-sale"); 
        String frClosed = request.getParameter("fr-closed"); 
        String frOwn = request.getParameter("fr-own"); 
        
        String fhFull = request.getParameter("fh-full");
        String fhSemi = request.getParameter("fh-semi");  
        String fhUn = request.getParameter("fh-un");     
        
        String searchTerm = sr1 + " " + sr2;
        
        filter.setKeywordTerm(sr1);
        filter.setPlaceTerm(sr2);
        
        filter.setPriceL(prL);
        filter.setPriceU(prU);
        filter.setSqAreaL(sqL);
        filter.setSqAreaU(sqU);
        filter.setBedroomL( StringUtils.isEmpty(brL) ? 0 : Integer.parseInt(brL) );
        filter.setBedroomU( StringUtils.isEmpty(brU) ? 0 : Integer.parseInt(brU) );
        filter.setBathroomL( StringUtils.isEmpty(bhL) ? 0 : Integer.parseInt(bhL) );
        filter.setBathroomU( StringUtils.isEmpty(bhU) ? 0 : Integer.parseInt(bhU) );
        filter.setForRent( StringUtils.isEmpty(frRent) ? false : true );
        filter.setForSale( StringUtils.isEmpty(frSale) ? false : true );
        filter.setForClosed( StringUtils.isEmpty(frClosed) ? false : true );
        filter.setForOwn( StringUtils.isEmpty(frOwn) ? false : true );
        filter.setFullyFurnished( StringUtils.isEmpty(fhFull) ? false : true );
        filter.setSemiFurnished( StringUtils.isEmpty(fhSemi) ? false : true );
        filter.setUnFurnished( StringUtils.isEmpty(fhUn) ? false : true );
                
        //ServiceResponse<List<Listing>> response = searchService.searchPostings(searchTerm, filter);
        //map.put("postings", response.getResponse());
        mav.setViewName("postings");
    }
       
    
    private List<Listing> trimListingsData(List<Listing> listings) {
        List<Listing> trimmedListings = new ArrayList<Listing>();
        if (listings != null && listings.size() > 0) {            
            for (Listing listing : listings) {
                try {                    
                    Listing trimmed = new Listing();
                    trimmed.setId(listing.getId());
                    trimmed.setTitle(listing.getTitle());
                    trimmed.setDisplayTitle(listing.getDisplayTitle());
                    trimmed.setUrlTitle(listing.getUrlTitle());
                    trimmed.setAddress(listing.getAddress());
                    trimmed.setPrimaryPhoto(listing.getPrimaryPhoto());
                    trimmed.setSqArea(listing.getSqArea());
                    trimmed.setLongMonthRate(String.format("%,.0f", listing.getLongMonthRateNum()));
                    trimmed.setShortDayRate(String.format("%,.0f", listing.getShortDayRateNum()));
                    trimmed.setShortWeekRate(String.format("%,.0f", listing.getShortWeekRateNum()));
                    trimmed.setShortMonthRate(String.format("%,.0f", listing.getShortMonthRateNum()));
                    trimmed.setAvailable(listing.isAvailable());
                    trimmed.setLeaseLongTerm(listing.isLeaseLongTerm());
                    trimmed.setLeaseShortTerm(listing.isLeaseShortTerm());
                    trimmed.setCommunity(listing.getCommunity());
                    trimmed.setCity(listing.getCity());
                    trimmedListings.add(trimmed);
                } 
                catch (Exception ex) {   }
            }
        }
        return trimmedListings;
    }
        
    private void terms(ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setViewName("terms");
    }
    
    private void privacy(ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setViewName("privacy");
    }
    
    private void works(ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setViewName("works");
    }
    
    private void rules(ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setViewName("rules");
    }
        
    private void featured(ModelAndView mav, Map map, HttpServletRequest request) {
        mav.setViewName("featured");
    }
}
